package org.young.common.bean;

import com.alibaba.fastjson.JSONObject;
import org.young.common.constant.BaseErrorInfoInterface;
import org.young.common.enums.CommonEnum;

import java.io.Serializable;

/**
 * @author young
 */
public class Result<T> implements Serializable {

	/**
	 * 响应代码
	 */
	private String code;
	/**
	 * 响应消息
	 */
	private String message;
	/**
	 * 响应结果
	 */
	private T      data;

	public Result() {
	}

	public Result(BaseErrorInfoInterface errorInfo) {
		this.code = errorInfo.getResultCode();
		this.message = errorInfo.getResultMsg();
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	/**
	 * 成功
	 *
	 * @return
	 */
	public static Result success() {
		return success(null);
	}

	/**
	 * 成功
	 *
	 * @param data
	 * @return
	 */
	public static <T> Result<T> success(T data) {
		Result<T> rb = new Result<T>();
		rb.setCode(CommonEnum.SUCCESS.getResultCode());
		rb.setMessage(CommonEnum.SUCCESS.getResultMsg());
		rb.setData(data);
		return rb;
	}

	/**
	 * 失败
	 */
	public static <T> Result<T> error(BaseErrorInfoInterface errorInfo) {
		Result<T> rb = new Result<T>();
		rb.setCode(errorInfo.getResultCode());
		rb.setMessage(errorInfo.getResultMsg());
		rb.setData(null);
		return rb;
	}

	/**
	 * 失败
	 */
	public static <T> Result<T> error(String code, String message) {
		Result<T> rb = new Result<T>();
		rb.setCode(code);
		rb.setMessage(message);
		rb.setData(null);
		return rb;
	}

	/**
	 * 失败
	 */
	public static <T> Result<T> error(String message) {
		Result<T> rb = new Result<T>();
		rb.setCode("-1");
		rb.setMessage(message);
		rb.setData(null);
		return rb;
	}

	@Override
	public String toString() {
		return JSONObject.toJSONString(this);
	}
}
